package com.github.hwangrq.minicat.server;

import com.github.hwangrq.minicat.container.*;
import com.github.hwangrq.minicat.servlet.HttpServlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @author hwangrq
 * @date 2021/3/16 23:09
 * @description 多线程请求处理类
 */
public class RequestProcessor extends Thread {

    private Socket socket;

    private Server server;

    public RequestProcessor(Socket socket, Server server) {
        this.socket = socket;
        this.server = server;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            // 封装response&request
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            HttpServlet httpServlet = findHttpServlet(request);
            if (httpServlet == null) {
                // 静态资源处理
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源Servlet
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private HttpServlet findHttpServlet(Request request) {
        HttpServlet servlet = null;
        Map<String, Mapper> serviceMap = server.getServiceMap();
        for (String key : serviceMap.keySet()) {
            List<Host> hosts = serviceMap.get(key).getHosts();
            for (Host host : hosts) {
                if (host != null) {
                    List<Context> contexts = host.getContexts();
                    String url = request.getUrl();

                    for (Context context : contexts) {
                        if (context != null) {
                            List<Wrapper> wrappers = context.getWrappers();
                            for (Wrapper wrapper : wrappers) {
                                String urlPattern = wrapper.getUrlPattern();
                                if (url.equals(urlPattern)) {
                                    servlet = (HttpServlet) wrapper.getServlet();
                                }
                            }
                        }
                    }
                }
            }
        }
        return servlet;
    }
}
